package me.zhengjie.modules.detailed_subject.service.Impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.detailed_subject.Entity.Subject;
import me.zhengjie.modules.detailed_subject.Entity.SubjectDto;
import me.zhengjie.modules.detailed_subject.Entity.SubjectVo;
import me.zhengjie.modules.detailed_subject.mapper.SubjectDao;
import me.zhengjie.modules.detailed_subject.service.SubjectService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectDao, Subject> implements SubjectService {

    @Override
    public List<SubjectDto> getSubject() {
        List<SubjectDto> finalList=new ArrayList<>();
        QueryWrapper<Subject> wrapper =new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<Subject> subjects = baseMapper.selectList(wrapper);
        for(Subject subject:subjects){
            SubjectDto  dto=new SubjectDto();
            dto.setId(subject.getId());
            dto.setLabel(subject.getLabel());

            QueryWrapper<Subject> wrapper1 =new QueryWrapper<>();
            wrapper1.eq("parent_id",subject.getId());
            List<Subject> subjects1 = baseMapper.selectList(wrapper1);

            List<SubjectDto> children=new ArrayList<>();
            for(Subject subject1:subjects1){
                SubjectDto  dto1=new SubjectDto();
                dto1.setId(subject1.getId());
                dto1.setLabel(subject1.getLabel());
                children.add(dto1);
            }
            dto.setChildren(children);
            finalList.add(dto);
        }

        return finalList;
    }

    @Override
    public void addsubject(SubjectVo subjectVo) {

        Subject subject=new Subject();
        String sid = RandomUtil.randomNumbers(16);
        subject.setId(sid);
        subject.setParentId(subjectVo.getId());
        subject.setLabel(subjectVo.getLabel());
        baseMapper.insert(subject);
    }

    @Override
    public void remocesubject(String id) {
        baseMapper.deleteById(id);
    }
}
